package com.gudong.user.client;

import com.gudong.model.except.ApplicationException;
import com.gudong.user.client.properties.WxConfigProperties;
import com.gudong.user.client.url.WxUrl;
import com.gudong.user.client.vo.WxLoginResponse;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Slf4j
@Component
public class WxClient {


    @Resource
    private RestTemplate restTemplate;
    @Resource
    private WxConfigProperties wxConfigProperties;

    /**
     * 微信登录
     *
     * @param code 微信code
     */
    public WxLoginResponse wxLogin(String code) {
        String url = WxUrl.WX_LOGIN_URL
                + "?appid=" + wxConfigProperties.getAppId()
                + "&secret=" + wxConfigProperties.getSecret()
                + "&js_code=" + code
                + "&grant_type=" + wxConfigProperties.getGrantType();
        ResponseEntity<WxLoginResponse> response = restTemplate.getForEntity(url, WxLoginResponse.class);
        log.info("微信登录返回结果:{}", response);
        if (response.getBody() == null) {
            throw new ApplicationException("数据请求失败，请重试");
        }
        WxLoginResponse wxLoginResponse = response.getBody();
        if (!wxLoginResponse.getErrcode().equals("0")) {
            throw new ApplicationException(wxLoginResponse.getErrmsg());
        }
        return wxLoginResponse;

    }
}
